package com.irishud.hudnavi.udp;

import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2016/10/1.
 */
public class UdpRxThread {
    String TAG = "UdpRxThread";
    public interface UdpReceivedListener{
        void onUdpReceived(byte[] data,int len);
    }
    String ip;
    InetAddress inetAddress;
    int    port;
    Thread thread;
    DatagramSocket socket;
    DatagramPacket packet;
    byte[] buff = new byte[4*1024];
    boolean isRunning = true;

    UdpReceivedListener listener;

    public UdpRxThread(String ipAddr, final int port){
        this.ip = ipAddr;
        this.port = port;
        try {
            inetAddress = InetAddress.getByName(ipAddr);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        try {
             packet =new DatagramPacket(buff,4*1024);
             socket = new DatagramSocket(this.port);
             socket.setReuseAddress(true);
        } catch (SocketException e) {
            e.printStackTrace();
        }

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while(isRunning){
                        Log.i(TAG,"udp data recieved ....Ip:"+ip+" port:"+port);
                        socket.receive(packet);
                        if(packet.getLength() > 0
                                && packet.getPort() == port
                                && packet.getAddress().equals(InetAddress.getByName(ip))){

                            Log.i(TAG,"udp data recieved ....Ip:"+ip+" port:"+port);

                            if(listener!=null){
                                listener.onUdpReceived(packet.getData(),packet.getLength());
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        Log.e(TAG,"Udp Rx Thread started listening on "+ipAddr + " port:"+port);
    }

    public void stop(){
        isRunning = false;
        thread.interrupt();
    }

    public void setUdpRxListener(UdpReceivedListener listener){
        this.listener = listener;
    }
}
